<template>
	<view class="m-cart">
		<u-toast ref="uToast" />
		<u-modal v-model="chooseShow" title="请选择您的就餐方式" :show-confirm-button="false">
			<view style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
				<view class="modalButton1">
					<u-button type="success" :plain="true" @click="handleButton1()">堂食</u-button>
				</view>
				<view class="modalButton2">
					<u-button type="primary" :plain="true" @click="handleButton2()">外卖</u-button>
				</view>
			</view>
		</u-modal>
		<u-modal v-model="goAddrShow" :content="goAddrContent" :mask-close-able="true" confirm-text="立即添加" @confirm="goAddress()"></u-modal>
		<!-- <u-popup v-model="chooseShow" mode="center" :click-mask-close="false" class="choosePopup">
				<view>请选择您的就餐方式</view>
		</u-popup> -->
		<!-- <u-modal v-model="chooseShow" :content="chooseContent"></u-modal> -->
		<u-modal v-model="modelShow" :content="content"></u-modal>
		<view class="fcb pl-32 pr-36 shop header-shop">
			<view class="flex items-center">
		
				<view class="pl-15 flex items-center"><text class="text-32">{{restaurantName}}</text>
				<text class="text-24 text-second">[{{address}}]</text></view>
			</view>
			<view class="desk text-30 w-100 fcc" @click="handleSelect()" v-if="dineStyle == '堂食'">
				<text>{{tableName}}</text>
				<u-select v-model="selectShow" mode="single-column" :list="tablelist"  @confirm="confirm"></u-select>
				<!-- <view class="mark"></view> -->
			</view>
			<view class="desk text-30 w-100 fcc" @click="handleSelect()" v-else-if="dineStyle == '外卖'">
				<text>{{detailAddress}}</text>
				<u-select v-model="selectShow" mode="single-column" :list="addrlist"  @confirm="confirm"></u-select>
			</view>
		</view>
		
		<CartShop class="card-shop-wrap" :data="cartShopData" :columns="columns" @numberComputed="numberComputed" />
		<CartPay :goodsNum="goodsNum" :subtotal="subtotal" :data="cartShopData" :columns="columns"/>
	</view>
</template>

<script>
	import config from '@/config'
	import { getShop, getTable } from '@/api/system/shop/shop'
	import { updateShoppingCart } from '@/api/system/shoppingCart/shoppingCart'
	import { isNull } from 'util';
	import {getAddress} from '@/api/system/address/address'
	
	export default {
		data() {
			return {
				goAddrShow: false,
				goAddrContent: '您还没有添加收货地址哦',
				dineStyle: '',
				chooseShow: false,
				chooseContent:"请选择您的就餐方式",
				modelShow: false,
				content: '本店暂时没有桌位空闲了哦!',
				restaurantName:"",
				address:"",
				cartShopData: [],
				columns: [],
				goodsNum: 0,
				subtotal: 0,
				tableId: '',
				addrId: '',
				tableName: '选择桌位',
				selectShow: false,
				detailAddress: '选择地址',
				tablelist: [],
				addrlist: []
			}
		},
		onLoad() {
			this.restaurantName = config.restaurantName;
			this.address = config.address;
			// console.log(this.$store.getters.dineStyle)
			// console.log(this.dineStyle)
			if (this.dineStyle === '' || this.dineStyle === null){
				this.chooseShow = true
			}
		},
		onShow() {
			this.getRes()
			this.dineStyle = this.$store.getters.dineStyle
			// console.log(this.$store.getters.dineStyle)
			if (this.dineStyle == '外卖'){
				this.handleButton2()
			} else if(this.dineStyle == '堂食'){
				this.handleButton1()
			}
			setTimeout(()=>{
				this.getData()
				this.$store.dispatch('updateCartShopData', this.cartShopData);
			},500)
		},
		mounted() {
			this.getRes()
			setTimeout(()=>{
				this.getData()
				this.$store.dispatch('updateCartShopData', this.cartShopData);
			},500)
		},
		methods: {
			goAddress(){
				this.$tab.navigateTo('/pages/address/add');
			},
			handleSelect(){
				if(this.dineStyle == '外卖' && this.addrlist.length == 0){
					this.goAddrShow = true
					return;
				}
				this.selectShow = true
			},
			handleButton1(){
				this.dineStyle = "堂食"
				this.$store.dispatch('updateDineStyle',this.dineStyle)
				this.chooseShow = false
				// console.log(this.$store.getters.dineStyle)
				
				// 获取空闲桌位
				getTable().then(res => {
					if(res.rows.length == 0){
						this.modelShow = true
						return
					}
					this.tablelist = res.rows.map(row => ({ 
						value: row.tableId, 
						label: row.tableName +'('+row.tableSize+'人)' ,
						}));
					// console.log(res)
					// console.log(this.tablelist)
				  resolve(res)
				}).catch(error => {
				  reject(error)
				})
			},
			handleButton2(){
				this.dineStyle = "外卖"
				this.$store.dispatch('updateDineStyle',this.dineStyle)
				this.chooseShow = false
				
				// 获取收货地址
				getAddress().then(res => {
					// this.addrlist = res.rows;
					// console.log(res)
					this.addrlist = res.rows.map(row => ({
						value: row.addressId,
						label: row.name+','+row.phone+','+row.detailAddress, 
					}));
					
					for (let obj of res.rows){
						if (obj.isDefault == 1){
							this.detailAddress = obj.detailAddress
							this.addrId = obj.addressId
							this.$store.dispatch('updateAddrId',this.addrId)
						}
					}
					// console.log(this.list)
				})
			},
			// 选择器
			confirm(e) {
				if (this.dineStyle == '堂食'){
					e.forEach(item => {
					  if (item.label) {
						this.tableName = item.label;
						this.tableId = item.value;
						}
					})
					this.$store.dispatch('updateTableData',this.tableId)
					console.log(e);
				} else if (this.dineStyle == '外卖'){
					e.forEach(item => {
					  if (item.label) {
						this.detailAddress = item.label;
						this.addrId = item.value;
						}
					})
					this.$store.dispatch('updateAddrId',this.addrId)
					console.log(e);
				}
				
				// console.log(this.$store.getters.table)
			},
			// 请求后端数据
			getRes(){
				// 获取菜品
				getShop().then(res => {
					this.cartShopData = res
					const hostname = config.baseUrl
					this.cartShopData = this.cartShopData.map(category => ({
					  ...category,
					  children: category.children.map(child => ({
					    ...child,
					    logo: hostname + child.logo
					  }))
					}));
					// console.log(res)
				  resolve(res)
				}).catch(error => {
				  reject(error)
				})
			},
			// 赋值数据
			getData(){
			    let columns = this.cartShopData.map(item=>{
			        return {
			            id:item.id,
			            name:item.name
			        }
			    })
			    this.columns = columns
			},
			numberComputed(val,item,ite){
				// console.log(val)
				// console.log(item)
				// console.log(ite)
			    this.cartShopData.forEach(itemWrap=>{
			       let num = 0,sum = 0;
			        if(ite.id===itemWrap.id){
			            itemWrap.children.forEach(childItem=>{
							console.log(childItem)
							console.log(val)
			                if(childItem.id===item.id){
								if((isNull(childItem.goodNum) || childItem.goodNum == 0) && val == 1){
									childItem.goodNum = val
									this.$store.dispatch('addToCart',childItem)
								} else if (childItem.goodNum == 1 &&  val == 0){
									this.$store.dispatch('removeFromCart',childItem)
								} else {
									childItem.goodNum = val
									this.$store.dispatch('updateGoodNum',childItem,val)
								} 
			                    childItem.goodNum = val
								sum += childItem.price
								// this.subtotal += childItem.price
			                }
			                num += childItem.goodNum
			            })
						// console.log("----")
						// console.log(itemWrap.goodNum)
						// console.log(num)
						// console.log(sum)
						// console.log("----")
						// if(itemWrap.goodNum == undefined || itemWrap.goodNum < num){
						// 	this.subtotal += sum
						// }else{
						// 	this.subtotal -= sum
						// }
			            itemWrap.goodNum = num
			        }
			        let findObj = this.columns.find(it=>it.id===itemWrap.id)
			        if(findObj){
			            this.$set(findObj,'goodNum',itemWrap.goodNum)
			        }
			    })
			
			    this.goodsNum = this.columns.reduce((curr,next)=>{
			        return curr+(next.goodNum||0)
			    },0)
				console.log(this.columns)
				console.log(this.goodsNum)
				// console.log(this.subtotal)
				this.subtotal = this.$store.getters.subtotal
				this.$store.dispatch('updateCartShopData', this.cartShopData);
				console.log(this.$store.getters.cartShopData)
				console.log(this.$store.getters.subtotal)
				console.log(this.$store.getters.shoppingCart)
				updateShoppingCart(this.$store.getters.shoppingCart).then(res=>{
					if (res.code == 200){
						this.$refs.uToast.show({
							title: '修改购物车成功',
							type: 'success'
						})
					}
					console.log(res)
				})
			},
		}
	}
</script>

<style lang="scss">
	.modalButton1{
		width: 60%;
		margin: 20px 0 10px 0;
	}
	.modalButton2{
		width: 60%;
		margin-bottom: 20px;
	}
	
	.text-30 {
		fonts-size: 30rpx;
	}

	.ml-25 {
		margin-left: 25rpx;
	}

	.h-80 {
		height: 80rpx;
	}

	.h-110 {
		height: 110rpx;
	}

	.text-24 {
		font-size: 24rpx;
	}

	.bg-white {
		background: white;
	}

	.fcb {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.flex {
		display: flex;
	}

	.items-center {
		align-items: center;
	}

	.px-32 {
		padding-left: 32rpx;
		padding-right: 32rpx;
	}

	.pl-32 {
		padding-left: 32rpx;
	}

	.text-white {
		color: white;
	}

	.pr-36 {
		padding-right: 36rpx;
	}

	.bg-white {
		background: white;
	}

	.fcc {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.bg-white {
		background: white;
	}

	.search {
		background: white;
		flex-shrink: 0;
		height: 100rpx;
	}

	.shop {
		flex-shrink: 0;
		height: 100rpx;
		background: white;
	}

	.card-shop-wrap {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.m-cart {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		display: flex;
		flex-direction: column;
	}

	.desk {
		position: relative;

			background: rgba(211,211,211,0.5);
		.mark {
			position: absolute;
			width: 110rpx;
			height: 20rpx;
			opacity: 0.6;
			bottom: 0;

		}
	}

	.header-shop {
		background: #F5F5F5;
	}
</style>
